#include <stdio.h>
#include <string.h>
#include "utils.h"

/*ČĽľô×Öˇű´ŽżŞÍˇşÍÄŠÎ˛ľÄżŐ°××Öˇű*/  
char *trimstr(char *string)
{  
    char *strp = NULL;
      
    trimrightblank(string);  
    strp = trimleftblank(string);  
      
    return strp;
}

/**
 *ČĽľô×Öˇű´ŽżŞÍˇľÄżŐ°××ÖˇűŁŹ˛˘ˇľťŘĐÂ×Öˇű´ŽÖ¸Őë
 */  
char * trimleftblank(char *string)  
{  
    char *strp = NULL;
      
    /*šýÂËżŐ×Öˇű´Ž*/  
    if(*string == '\0'){
        return string;
    }
    /*şöÂÔÍˇ˛żľÄ żŐ¸ń '/r' '/n' '/t'*/
    strp = string;
    while(*strp == ' ' || *strp == '\t' || *strp == '\r' || *strp == '\n'){
        strp++;
    }  
      
    return strp;  
}  
  
/*ČĽľô×Öˇű´ŽÄŠÎ˛ľÄżŐ°××Öˇű*/  
void trimrightblank(char *string)  
{  
    unsigned long strlenth = 0;  
      
    /*šýÂËżŐ×Öˇű´Ž*/
    if(*string == '\0'){
        return;  
    }  
      
    /*ČĽľôÎ˛˛żľÄ żŐ¸ń '/r' '/n' '/t'*/  
    strlenth = strlen(string);      
    while(' ' == string[strlenth - 1] || '\t' == string[strlenth - 1]   
          || '\r' == string[strlenth - 1] || '\n' == string[strlenth - 1]){  
        strlenth--;  
    }  
    string[strlenth] = '\0';  
}

/*Will change the original string. Please backup the original string before call this function
 *Make sure ret_segment is large enough.
 */
char *get_delimited_string(char *string, char delim, char *ret_segment)
{
	char *cur_str = string;
	char *cur_buf = ret_segment;

	if(*cur_str == '\0'){
		return NULL;
	}
	
	for(;*cur_str != delim&&*cur_str != '\0';cur_str++,cur_buf++){
		*cur_buf = *cur_str;
	}
	*cur_buf = '\0';
	
	if(*cur_str == '\0'){
		return cur_str;
	}else{
		return ++cur_str;
	}
}
